package frame;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import frame.bean.ActionMapping;
import frame.bean.Result;

public class ActionServlet extends HttpServlet {

	private ActionMappingManager manager;
	@Override
	public void init() throws ServletException {
		manager = new ActionMappingManager();
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		String actionName = uri.substring(uri.lastIndexOf("/")+1, uri.lastIndexOf(".action"));
		ActionMapping actionMapping = manager.getActionMapping(actionName);
		String className = actionMapping.getClassName();
		String method = actionMapping.getMethod();
		Map<String, Result> results = actionMapping.getResult();
		try {
			Class<?> clazz = Class.forName(className);
			Object obj = clazz.newInstance();
			Method m = clazz.getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);
			String resFlag = (String) m.invoke(obj, request,response);
			Result result = results.get(resFlag);
			String type = result.getType();
			String page = result.getPage();
			if("redirect".equals(type)){
				response.sendRedirect(request.getContextPath()+page);
			}else{
				request.getRequestDispatcher(page).forward(request, response);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
